import { Component, OnInit } from '@angular/core';
import { Sort } from '../../models/Sort'

@Component({
    selector: 'bubble-sort',
    templateUrl: './bubble-sort.component.html',
    styleUrls: ['./bubble-sort.component.scss']
})
export class BubbleSortComponent implements OnInit {
    constructor() { }
    ngOnInit() {
        const nums = [3, 5, 2, 6, 1];
        console.log('排序前 nums: ', nums);

        const bubbleSort = new BubbleSort<number>();
        bubbleSort.sort(nums);
        console.log('排序后 nums: ', nums);


        const persons: Person[] = [];
        for (let i = 0; i < 5; i++) {
            const person = new Person(`a-${5-i}`, 5-i);
            persons.push(person);
        }
        console.log('排序前 persons: ', persons);

        const bubbleSort2 = new BubbleSort<Person>();
        bubbleSort2.sort(persons, person => person.age);
        console.log('排序后 persons: ', persons);

    }
}

class Person {
    public name: string;
    public age: number;

    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}

class BubbleSort<T> extends Sort<T> {
    constructor() {
        super();
    }
    sort (datas: T[], prop?: string | ((p: T) => any)) {
        for (let i = datas.length - 1; i > 0; i--) {
            for (let j = 0; j < i; j++ ) {
                let a1 = null;
                let b1 = null;

                if (!prop) {
                    a1 = datas[j+1];
                    b1 = datas[j];
                } else if (typeof prop === 'string') {
                    a1 = datas[j+1][prop];
                    b1 = datas[j][prop];
                } else if (typeof prop === 'function') {
                    a1 = prop(datas[j+1]);
                    b1 = prop(datas[j]);
                }                

                if (this.less(a1, b1)) {
                    this.exch(datas, j, j+1);
                }
            } 
        }
    }
}